#import <UIKit/UIKit.h>
#import <Foundation/Foundation.h>
#import "PushPackage.h"
#import "GJIMMessageModel.h"
#import "GJIMSessionService.h"
#import "GJIMMessageService.h"
#import "BDEncrypt.h"
#import "BDChatBasicCell.h"
#import "GJIMDBService.h"
#import "GJIMSessionToken.h"

%hook GJIMSessionService

- (id)p_handlePushPackage:(PushPackage *)pkg {
    switch (pkg.messageType) {
        case 55: { // 撤回
            NSLog(@"[BLUEDHOOK] %@ 撤回消息已被拦截。", pkg.name);
            
            GJIMSessionToken *sessionToken = [objc_getClass("GJIMSessionToken") gji_sessionTokenWithId:pkg.sessionId type:2];
            [objc_getClass("GJIMDBService") gji_getMessagesWithToken:sessionToken complete:^(id data) {
                GJIMMessageModel *targetMsg;
                for (GJIMMessageModel *msg in data) {
                    if (msg.msgId == pkg.messageId) {
                        targetMsg = msg;
                        break;
                    }
                }
                
                if (targetMsg == nil) {
                    NSLog(@"[BLUEDHOOK] Warning: cannot find msgid %llu from %d in message service, canceled tagging.", pkg.messageId, pkg.from);
                    for (GJIMMessageModel *msg in data) {
                        if (msg.fromId == pkg.from) {
                            targetMsg = msg;
                            break;
                        }
                    }
                    targetMsg.type = 1;
                    targetMsg.msgId = pkg.messageId;
                    targetMsg.sendTime = pkg.timestamp;
                    targetMsg.msgExtra = @{@"BLUED_HOOK_IS_RECALLED": @1};
                    targetMsg.content = @"对方撤回了一条消息，但已错过接收原始消息无法复原。";
                    [self addMessage:targetMsg];
                    return;
                }
                
                targetMsg.msgExtra = @{@"BLUED_HOOK_IS_RECALLED": @1};
                [self updateMessage:targetMsg];
            }];
            
            return nil;
        }
        case 24: {
            pkg.messageType = 2;
            pkg.contents = [objc_getClass("BDEncrypt") decryptVideoUrl:pkg.contents];
            pkg.msgExtra = @{@"BLUEDHOOK_IS_SNAPIMG": @1};
            break;
        }
        default:
            break;
    }
    
    return %orig(pkg);
}

%end


%hook UITableViewCell

- (id)contentView {
    NSString *cellClassName = [NSString stringWithFormat:@"%@", [self class]];
    
    if (![cellClassName containsString:@"PrivateOther"]) {
        return %orig;
    }
    
    UIView *contentView = %orig;
    GJIMMessageModel *msg = [[(BDChatBasicCell*)self message] copy];
    
    if (msg == nil) {
        return contentView;
    }
    
    NSLog(@"handing msg type:%llu, msgID: %llu, msgContent: %@\nBLUEDHOOK_IS_SNAPIMG: %@, BLUED_HOOK_IS_RECALLED: %@", 
          msg.type, msg.msgId, msg.content, 
          [msg.msgExtra objectForKey:@"BLUEDHOOK_IS_SNAPIMG"], 
          [msg.msgExtra objectForKey:@"BLUED_HOOK_IS_RECALLED"]);
    
    if (msg.type == 24) {
        msg.type = 2;
        msg.content = [objc_getClass("BDEncrypt") decryptVideoUrl:msg.content];
        msg.msgExtra = @{@"BLUEDHOOK_IS_SNAPIMG": @1};
        GJIMSessionService *sessionService = [objc_getClass("GJIMSessionService") sharedInstance];
        [sessionService updateMessage:msg];
        return contentView;
    }
    
    NSInteger labelTag = 1069;
    CGFloat labelPosTop = contentView.frame.size.height - 12;
    CGFloat labelPosLeft = [[contentView subviews][2] frame].origin.x;
    
    switch (msg.type) {
        case 1:
            labelPosTop -= 8;
            labelPosLeft += 12;
            break;
        case 3:
            labelPosLeft += 12;
            break;
        default:
            break;
    }
    
    CGRect labelFrame = CGRectMake(labelPosLeft, labelPosTop, contentView.frame.size.width, 12);
    UILabel *label = [self viewWithTag:labelTag];
    
    if (label == nil) {
        label = [[UILabel alloc] init];
        [label setFrame:labelFrame];
        [label setFont:[UIFont systemFontOfSize:9]];
        label.textColor = [UIColor grayColor];
        label.tag = labelTag;
        label.numberOfLines = 1;
        [self addSubview:label];
    }
    
    NSArray *keys = [msg.msgExtra allKeys];
    if (msg.msgId == 0 || [keys count] == 0) {
        return contentView;
    }
    
    NSString *labelText = @"";
    if ([keys containsObject:@"BLUEDHOOK_IS_SNAPIMG"]) {
        labelText = @"该照片由闪照转换而成。";
    } else if([keys containsObject:@"BLUED_HOOK_IS_RECALLED"]) {
        labelText = @"对方尝试撤回此消息，已被阻止。";
        if ([msg.content containsString:@"burn-chatfiles"]) {
            labelText = @"该闪照已被对方撤回。";
        }
    }
    
    label.text = labelText;
    [label setFrame:labelFrame];
    
    return contentView;
}

%end


%ctor {
    %init(GJIMSessionService = objc_getClass("GJIMSessionService"),
          UITableViewCell = objc_getClass("UITableViewCell"));
    
    NSLog(@"BLUEDHOOK loaded successfully!");
}